﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Data;
using Ionic.Zip;
using System.IO;

namespace ServerBackupAndMail
{
    class Utils
    {

        public static void sendEmail(string SenderEmail, string displaySenderName, string SenderPassword, string To, string CC, string Subject, string Body, string Attachment)
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(SenderEmail, displaySenderName);
            msg.To.Add(new MailAddress(To));
            if (CC.Length > 0)
            {
                msg.CC.Add(new MailAddress(CC));
            }
            msg.Subject = Subject;
            msg.Body = Body;
            msg.IsBodyHtml = true;
            string[] attach=Attachment.Split(',');
            foreach(String str in attach)
            {
                if(str.Length > 0)
                    msg.Attachments.Add(new Attachment(str));
            }
            
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Credentials = new NetworkCredential(SenderEmail, SenderPassword);
            smtp.EnableSsl = true;
            try
            {
                smtp.Send(msg);
            }
            catch (Exception ex)
            {
                
            }
        }

        public static void SqlBackup(string ServerName, string DatabaseName, string strFileName)
        {
            try
            {
                string command = @"BACKUP DATABASE "+ DatabaseName +" TO DISK='" + strFileName + "'";
                SqlCommand oCommand = null;
                SqlConnection oConnection = null;
                oConnection = new SqlConnection("Data Source="+ ServerName +";Initial Catalog="+ DatabaseName +";Integrated Security=True");
                if (oConnection.State != ConnectionState.Open)
                    oConnection.Open();
                oCommand = new SqlCommand(command, oConnection);
                oCommand.ExecuteNonQuery();


            }
            catch (Exception ex)
            {
                
            }
        }

        public static void zipFile(string sourceFile, string destinationFile)
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AddFile(sourceFile);
                zip.Save(destinationFile);
            }
        }

        public static void zipFolder(string sourceFolder, string destinationFile)
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(sourceFolder);
                zip.Save(destinationFile);
            }
        }

        public static void unZipFile(string sourceFile, string destinationFolder)
        {
            string zipToUnpack = sourceFile;
            string unpackDirectory = destinationFolder;
            using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
            {
                // here, we extract every entry, but we could extract conditionally
                // based on entry name, size, date, checkbox status, etc.  
                foreach (ZipEntry e in zip1)
                {
                    e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }

        //Call this function
        public static void CopyLastetDirectory(string sourceDirectory, string targetDirectory, DateTime dtTargetDate)
        {
            DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
            DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
            try
            {
                CopyAllLastestFiles(diSource, diTarget, dtTargetDate);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                diSource = null;
                diTarget = null;
            }
        }

        //this is helping function of CopyLastetDirectory
        private static void CopyAllLastestFiles(DirectoryInfo source, DirectoryInfo target, DateTime dtTargetDate)
        {
            // Check if the target directory exists, if not, create it.
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy each file into it’s new directory.
            foreach (FileInfo fi in source.GetFiles())
            {
                //Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
                if (fi.LastWriteTime.Date >= dtTargetDate.Date && !fi.Name.Contains("Web.config"))
                    fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            // Copy each subdirectory using recursion.
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                // Folder names that you want to omit
                if (diSourceSubDir.Name.Contains(".svn") || diSourceSubDir.Name.Contains("Vagaro.BackupService"))
                    continue;
                DirectoryInfo nextTargetSubDir =
                target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAllLastestFiles(diSourceSubDir, nextTargetSubDir, dtTargetDate);
                nextTargetSubDir = null;
            }
        }

    }
}
